package service

import (
	"context"
	"go-shop-admin/internal/dao"
	"go-shop-admin/internal/model"
	"go-shop-admin/pkg/e"
	"go-shop-admin/pkg/serializer"
	"go-shop-admin/pkg/zydhjwt"
	"go-shop-admin/pkg/zydhlog"
)

//登录

type LoginService struct {
	Account  string `form:"account" json:"account" binding:"required,alphanum"  _:"comment:登录账号"`
	Password string `form:"password" json:"password"  binding:"required,alphanum" _:"comment:密码 sha1加密"` // checkPsw  0x7C== |  0x2c == ,  0x2e == .  0x2d == -  0x5f == _
	Ipv4     string `form:"ipv4" json:"ipv4" binding:"required,ip"`
	Ipv6     string `form:"ipv6" json:"ipv6" `
	//验证码
	Key  string `form:"key" binding:"required" `
	Dots string `form:"dots" binding:"required" `
}

// Login 登录
func (s *LoginService) Login(ctx context.Context) *serializer.Response {
	var err error
	//根据ip地址查看某一段时间内的登录次数，限制x分钟类的登录次数

	//校验验证码
	//err = go_captcha.CheckVerifyCode(s.Key, s.Dots)
	//if err != nil {
	//	return serializer.NewResponse(e.ErrorCheckCaptcha, e.TipsNil, err.Error(), nil)
	//}
	//根据账号查询用户是否存在
	var auth *model.Auth
	var ok bool
	authDao := dao.NewAuthDao(ctx)

	whereMap := dao.WhereStruct{Where: map[string]interface{}{
		"account": s.Account,
	}}

	auth, ok, err = authDao.ExistOrNotByWhere(whereMap)
	//不存在
	if !ok || err != nil {
		zydhlog.Error(err.Error())
		//写入登录日志
		go WriteAuthLoginLog(ctx, NewAuthLoginLogService(1, s.Account, e.TipsNotExistUser, s.Ipv4, s.Ipv6))
		return serializer.NewResponse(e.ErrorExistAuth, err.Error(), e.TipsNotExistUser, nil)
	}

	//存在-检查状态
	if auth.Status != dao.DisableStatus {
		zydhlog.Error("不可登录,该用户已经被禁用")
		//写入登录日志
		go WriteAuthLoginLog(ctx, NewAuthLoginLogService(1, s.Account, e.TipsErrorAuthIsDisable, s.Ipv4, s.Ipv6))
		return serializer.NewResponse(e.ErrorAuthIsDisable, err.Error(), e.TipsErrorAuthIsDisable, nil)
	}

	//存在 - 校验密码
	if !dao.CheckPassword(auth.Password, s.Password) {
		zydhlog.Error(e.TipsErrorPwd)
		return serializer.NewResponse(e.ErrorNotCompare, e.TipsNil, e.TipsErrorPwd, nil)
	}

	//密码校验通过

	//设置jwt-token
	token, err := zydhjwt.GenerateToken(auth.ID, auth.Account, 0)
	if err != nil {
		zydhlog.Error(err.Error())
		return serializer.NewResponse(e.ErrorAuthToken, err.Error(), e.TipsGeneral, nil)
	}

	wg.Add(1)
	//更改账号的登录次数 go() 跑的太快，使用wg等待一下
	go func(id uint, loginNum uint, dao **dao.AuthDao) {
		defer wg.Done()
		if err = authDao.AuthUpdate(id, &model.Auth{LoginNum: loginNum}); err != nil {
			zydhlog.Error(err.Error())
		}
	}(auth.ID, auth.LoginNum+1, &authDao)

	//写入登录日志
	wg.Add(1)
	go WriteAuthLoginLog(ctx, NewAuthLoginLogService(1, s.Account, e.TipsSuccessLogin, s.Ipv4, s.Ipv6))

	wg.Wait()

	//返回token和管理员信息
	return serializer.NewResponse(e.Success, e.TipsOk, e.TipsSuccessLogin, serializer.TokenData{
		Token: token,
		Auth:  serializer.BuildAuth(auth),
	})
}
